#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/22
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import json, session
from project.define import AxiosMessage
from project.modules import DeviceGate, DeviceCamera, DeviceLED168, DeviceCashier


class Messager(AxiosMessage):
    """
    消息管理器
    """
    def __init__(self) -> None:
        super().__init__()
        self.__view_names = {"gate":"閘機","camera":"相機","led":"顯示屏","cashier":"收費處"}

    def __get_data(self, view, **data):
        """
        获取数据
        """
        r = None
        if view == "gate":
            r = DeviceGate.selected_data(**data)
        elif view == "camera":
            r = DeviceCamera.selected_data(**data)
        elif view == "led":
            r = DeviceLED168.selected_data(**data)
        elif view == "cashier":
            r = DeviceCashier.selected_data(**data)
        if r:
            return self.json_data(**r.to_dict())
        return "Fail"

    def __reset_filter(self, view):
        """
        重置条件
        """
        if view == "gate":
            filter_name = "GateFilter"
        elif view == "camera":
            filter_name = "CameraFilter"
        elif view == "led":
            filter_name = "LEDFilter"
        elif view == "cashier":
            filter_name = "CashierFilter"
        filters = session.get(filter_name)
        if filters:
            del session[filter_name]
        return "OK"

    def __set_filter(self, view, **data):
        """
        设置条件
        """
        if view == "gate":
            session['GateFilter'] = data
        elif view == "camera":
            session['CameraFilter'] = data
        elif view == "led":
            session['LEDFilter'] = data
        elif view == "cashier":
            session['CashierFilter'] = data
        return "OK"

    def __delete_data(self, view, **data):
        """
        删除数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view == "gate":
                ret = DeviceGate.delete_data(**data)
            elif view == "camera":
                ret = DeviceCamera.delete_data(**data)
            elif view == "led":
                ret = DeviceLED168.delete_data(**data)
            elif view == "cashier":
                ret = DeviceCashier.delete_data(**data)
        if ret:
            return self.success(f"{data_name}刪除成功")
        return self.warning(f"{data_name}刪除失敗")
        
    def __modify_data(self, view, **data):
        """
        修改数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view == "gate":
                ret = DeviceGate.modify_data(**data)
            elif view == "camera":
                ret = DeviceCamera.modify_data(**data)
            elif view == "led":
                ret = DeviceLED168.modify_data(**data)
            elif view == "cashier":
                ret = DeviceCashier.modify_data(**data)
        if ret:
            if isinstance(ret, dict):
                return self.success(f"{data_name}更新成功")
            elif ret == "ignore":
                return self.warning(f"{data_name}沒有更新")
        return self.warning(f"{data_name}更新失敗")

    def __insert_data(self, view, **data):
        """
        插入数据
        """
        def get_gate_name():
            gate_id = data.get('GateID')
            r = DeviceGate.query.filter_by(GateID=gate_id).first()
            if r:
                data['GateName'] = r.GateName
            return data

        data_name = self.__view_names.get(view)
        if data_name:
            if view == "gate":
                ret = DeviceGate.insert_data(**data)
            elif view == "camera":
                ret = DeviceCamera.insert_data(**get_gate_name())
            elif view == "led":
                ret = DeviceLED168.insert_data(**get_gate_name())
            elif view == "cashier":
                ret = DeviceCashier.insert_data(**data)
        if ret:
            return self.success(f"新增{data_name}成功")
        return self.warning(f"新增{data_name}失敗")

    def post_data_handler(self, **kwargs):
        """
        POST数据处理
        """
        view = kwargs.get("View")
        for k, v in kwargs.items():
            if k == "Insert":
                return self.__insert_data(view, **v)
            elif k == "Modify":
                return self.__modify_data(view, **v)
            elif k == "Delete":
                return self.__delete_data(view, **v)
            elif k == "SetFilter":
                return self.__set_filter(view, **v)
            elif k == "ResetFilter":
                return self.__reset_filter(view)
            elif k == "GetData":
                return self.__get_data(view, **v)
        return self.error("請求錯誤，請聯係管理員")
        
    def __generate_page_data(self, *args):
        """
        生成页面数据
        """
        return {
            "ColumnName":args[0], 
            "ColumnNameJSON": json.dumps(args[0],ensure_ascii=False), 
            "TableDatas": args[1],
            "Filters": args[2],
            "FiltersJSON": json.dumps(args[2],ensure_ascii=False),
        }

    def cashier_page_data(self):
        """
        收费处页面
        """
        filters = session.get("CashierFilter")
        if not filters:
            filters = dict.fromkeys(("CashierName", "Position"))
        data_filters = DeviceCashier.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = DeviceCashier.query.all()
        else:
            table_datas = DeviceCashier.query.filter(*data_filters).all()
        column_name = DeviceCashier.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def led_page_data(self):
        """
        显示屏页面
        """
        filters = session.get("LEDFilter")
        if not filters:
            filters = dict.fromkeys(("GateName", "Position"))
        data_filters = DeviceLED168.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = DeviceLED168.query.all()
        else:
            table_datas = DeviceLED168.query.filter(*data_filters).all()
        column_name = DeviceLED168.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def camera_page_data(self):
        """
        相机页面
        """
        filters = session.get("CameraFilter")
        if not filters:
            filters = dict.fromkeys(("GateType","GateName", "VehicleType", "Position"))
        data_filters = DeviceCamera.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = DeviceCamera.query.all()
        else:
            table_datas = DeviceCamera.query.filter(*data_filters).all()
        column_name = DeviceCamera.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def gate_page_data(self):
        """
        闸机页面
        """
        filters = session.get("GateFilter")
        if not filters:
            filters = dict.fromkeys(("GateType","GateName"))
        data_filters = DeviceGate.generate_filters(**filters)
        if len(data_filters) == 0:
            table_datas = DeviceGate.query.all()
        else:
            table_datas = DeviceGate.query.filter(*data_filters).all()
        column_name = DeviceGate.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])
